package com.ccepc.algmanage.controller;

import com.ccepc.algmanage.service.AlgConfigPointsService;
import com.ccepc.algmanage.service.ObsService;
import com.ccepc.algmanage.utils.AuthInfoUtils;
import com.ccepc.algmanage.utils.CommonUtils;
import com.ccepc.algmanage.utils.HkUtils;
import com.ccepc.common.log.annotation.SysLog;
import com.ccepc.demo.api.constants.RecordConstants;
import com.ccepc.demo.api.dto.HkAuthsDto;
import com.ccepc.demo.api.entity.AlgConfigPoints;
import com.obs.services.ObsClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RestController
@Slf4j
@RequestMapping("/file" )
@Api(value = "obs", tags = "图片上传和展示")
public class ObsController {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.access-key}")
    private String accessKey;
    @Value("${oss.secret-key}")
    private String secretKey;
    @Value("${oss.bucket-name}")
    private String bucketName;

    @Resource
    private AlgConfigPointsService algConfigPointsService;

    @Resource
    private ObsService obsService;

    @ApiOperation(value = "图片上传")
    @SysLog("图片上传" )
    @PostMapping("/upload")
    @PreAuthorize("@pms.hasPermission('algmanage_obs_upload')" )
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file){
        return obsService.uploadImage(file, new ObsClient(accessKey, secretKey, endpoint), bucketName);
    }

    @ApiOperation(value = "图片展示")
    @SysLog("图片展示" )
    @GetMapping("/display/{filename}")
    @PreAuthorize("@pms.hasPermission('algmanage_obs_display')" )
    public ResponseEntity<Object> getImage(@PathVariable String filename) {
        return obsService.displayImage(filename, new ObsClient(accessKey, secretKey, endpoint), bucketName);
    }

    @ApiOperation(value = "图片删除")
    @SysLog("图片删除" )
    @DeleteMapping("/delete")
    @PreAuthorize("@pms.hasPermission('algmanage_obs_delete')" )
    public ResponseEntity<Object> deleteFile(@RequestParam("fileName") String fileName) {
        return obsService.deleteImage(fileName, new ObsClient(accessKey, secretKey, endpoint), bucketName);
    }

    @ApiOperation(value = "手动抓图存储到华为云")
    @SysLog("手动抓图存储到华为云" )
    @PostMapping("/getCameraImg")
    public ResponseEntity<Object> getCameraImg(@RequestBody HkAuthsDto hkAuthsDto) {
        String cameraIndexCode = hkAuthsDto.getCameraIndexCode();
        // 使用相机索引代码作为文件名
        String fileName = RecordConstants.IMG_INDEX + cameraIndexCode + ".jpg";
        byte[] imageData = null;
        try {
            HkUtils hkUtils = new HkUtils(hkAuthsDto.getHkAuths());
            // 获取图片的URL，将图片上传至华为云
            String picUrl = CommonUtils.stringToJson(hkUtils.getPicByCameraIndexCode(cameraIndexCode))
                    .getJSONObject("data").getString("picUrl");
            if (picUrl != null) {
                imageData = obsService.uploadAndShowImg(new ObsClient(accessKey, secretKey, endpoint), bucketName, fileName, picUrl);
            }
            if (imageData != null) {
                // 根据创建标签来指定是否需要创建
                if (hkAuthsDto.getLabel()) {
                    // 保存algConfigPoints
                    AlgConfigPoints algConfigPoints = new AlgConfigPoints();
                    algConfigPoints.setLatestImg(fileName);
                    algConfigPoints.setDeviceNo(cameraIndexCode);
                    algConfigPoints.setCreatedBy(AuthInfoUtils.getUserId());
                    algConfigPoints.setCreatedTime(LocalDateTime.now());
                    algConfigPointsService.save(algConfigPoints);
                }
                // 返回带有图片字节数组的ResponseEntity
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.IMAGE_JPEG); // 设置响应头为图片类型
                return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        // 返回错误响应
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

}
